import { Component, OnDestroy, Inject, Optional, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {
  SocialService,
  ITokenService,
  DA_SERVICE_TOKEN,
} from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { StartupService } from '@core';
import { HttpService, ServiceInfo } from 'lbf';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService],
})
export class UserLoginComponent implements OnDestroy, OnInit {

  form: FormGroup;
  error = '';
  type = 0;
  loading = false;

  constructor(
    fb: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    public msg: NzMessageService,
    private lbservice: HttpService,
    private serinfo: ServiceInfo,
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(2)]],
      password: [null, Validators.required],
      remember: [true],
    });
    modalSrv.closeAll();
  }

  // #region fields

  get userName() {
    return this.form.controls.userName;
  }
  get password() {
    return this.form.controls.password;
  }

  get remember() {
    return this.form.controls.remember;
  }

  // #endregion

  submit() {
    this.error = '';

    this.userName.markAsDirty();
    this.userName.updateValueAndValidity();
    this.password.markAsDirty();
    this.password.updateValueAndValidity();
    if (this.userName.invalid || this.password.invalid) return;

    this.loading = true;
    this.lbservice.login(this.userName.value, this.password.value).then((resdata) => {
      this.loading = false

      if (resdata.code < 1) {
        this.msg.error(resdata.errmsg);
        return;
      }

      // 保存用户名
      if (this.remember.value)
        localStorage.setItem("lastLoginUser", this.userName.value);
      else
        localStorage.setItem("lastLoginUser", "");


      this.reuseTabService.clear();
      this.tokenService.clear();

      this.tokenService.set({
        token: resdata.message.LOGINTOKEN,
        name: this.userName.value,
        aac003: resdata.message.AAC003,
        aaf001: resdata.message.DEPT,
        time: +new Date(),
      });

      this.serinfo.setUser({
        aac003: resdata.message.AAC003,
        name: this.userName.value,
        dept: resdata.message.DEPT,
        usertype: resdata.message.USERTYPE,
        ks: resdata.message.KS
      });
      let c = localStorage.getItem('usercache');
      if (!c) {
        c = "{}";
      }

      const usercache = JSON.parse(c);
      if (!usercache[this.serinfo.user.name]) {
        usercache[this.serinfo.user.name] = { li: [], cdr: [] };
      }

      usercache[this.serinfo.user.name].cdr.push(new Date());
      usercache[this.serinfo.user.name].roleid = resdata.message.ROLEID;
      localStorage.setItem('usercache', JSON.stringify(usercache));



      //  this.serinfo.setUser({ userName: this.userName.valid, aac003: resdata.message.AAC003, usertype: resdata.message.USERTYPE });
      this.startupSrv.load().then(() => this.router.navigate(['/']));
    })


    // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
    // this.http
    //   .post('/login/account?_allow_anonymous=true', {
    //     type: this.type,
    //     userName: this.userName.value,
    //     password: this.password.value,
    //   })
    //   .subscribe((res: any) => {
    //     if (res.msg !== 'ok') {
    //       this.error = res.msg;
    //       return;
    //     }
    //     // 清空路由复用信息
    //     this.reuseTabService.clear();
    //     // 设置用户Token信息
    //     this.tokenService.set(res.user);
    //     // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
    //     this.startupSrv.load().then(() => {
    //       let url = this.tokenService.referrer.url || '/';
    //       if (url.includes('/passport')) url = '/';
    //       this.router.navigateByUrl(url);
    //     });
    //   });
  }


  ngOnInit(): void {

    this.userName.setValue(localStorage.getItem("lastLoginUser"));
  }
  ngOnDestroy(): void {

  }

}
